package com.doghome.mysb.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.antherd.smcrypto.sm3.Sm3;
import com.doghome.mysb.dao.UserMapper;
import com.doghome.mysb.entity.User;
import com.doghome.mysb.exception.NameAndPasswordException;
import com.doghome.mysb.service.LoginService;
import com.doghome.mysb.utils.JwtUtil;

@Service
public class LoginServiceImpl implements LoginService {
	
	
	private UserMapper userMapper;
	
	private StringRedisTemplate redisTemplate;
	
	
	@Autowired
	public LoginServiceImpl(UserMapper userMapper, StringRedisTemplate redisTemplate) {
		this.userMapper = userMapper;
		this.redisTemplate = redisTemplate;
	}



	@Override
	public Map<String,Object> login(String userCode, String password) {
		User user = userMapper.selectByUserCode(userCode);
		String sign = Sm3.sm3(password);
		if(user == null || !sign.equals(user.getUserpassword())) {
			throw new NameAndPasswordException();
		}
		String jwt = JwtUtil.createToken(user.getId());
		redisTemplate.opsForValue().set(user.getId().toString(), jwt, 30, TimeUnit.MINUTES);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("jwt", jwt);
		map.put("userName",user.getUsername());
		return map;
	}

}
